package com.ctshk.rpc.starvip.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ctshk.common.constant.CurrencyRateExchangeConstant;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.Currency;
import com.ctshk.common.enums.SystemBusinessType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.utils.CalcIntegralUtil;
import com.ctshk.common.utils.MD5Util;
import com.ctshk.rpc.starvip.dto.UserMemberBasicInformationDTO;
import com.ctshk.rpc.starvip.dto.start_vip.transaction.LoyTransaction;
import com.ctshk.rpc.starvip.dto.start_vip.transaction.TrainIntegralDTO;
import com.ctshk.rpc.starvip.dto.start_vip.user.Contact;
import com.ctshk.rpc.starvip.dto.start_vip.user.ListOfLoyMemberDominantTier;
import com.ctshk.rpc.starvip.dto.start_vip.user.LoyMember;
import com.ctshk.rpc.starvip.dto.start_vip.user.LoyMemberDominantTier;
import com.ctshk.rpc.starvip.enums.transaction.StarVipCurrencyCode;
import com.ctshk.rpc.starvip.enums.transaction.StarVipTransactionProduct;
import com.ctshk.rpc.starvip.enums.transaction.StarVipTransactionSubType;
import com.ctshk.rpc.starvip.enums.transaction.StarVipTransactionType;
import com.ctshk.rpc.starvip.req.*;
import com.ctshk.rpc.starvip.req.member.MembershipVerificationReq;
import com.ctshk.rpc.starvip.req.transaction.StarVipTransactionIntegralReq;
import com.ctshk.rpc.starvip.req.transaction.StarVipTransactionReq;
import com.ctshk.rpc.starvip.req.user.UserInfoQueryReq;
import com.ctshk.rpc.starvip.service.IStarVipBusinessService;
import com.ctshk.rpc.starvip.service.IStarVipMemberService;
import com.ctshk.rpc.starvip.service.IStarVipTransactionService;
import com.ctshk.rpc.starvip.service.IStarVipUserService;
import com.ctshk.rpc.system.service.IMainDataCurrencyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @BelongsProject: ctshk-cloud
 * @BelongsPackage: com.ctshk.rpc.starvip.service.impl
 * @Author: hef
 * @CreateTime: 2021-04-22 11:34
 * @Description: 描述
 */
@Slf4j
@DubboService
public class StarVipBusinessServiceImpl implements IStarVipBusinessService {
    @Autowired
    private IStarVipUserService starVipUserService;
    @Autowired
    private IStarVipMemberService starVipMemberService;
    @Autowired
    private IStarVipTransactionService transactionService;
    @DubboReference
    private IMainDataCurrencyService mainDataCurrencyService;


    @Override
    public Result<UserMemberBasicInformationDTO> getUserMemberBasicInformation(UserMemberBasicInformationReq req) {
        log.info("【星赏會VIP-查询会员】入参請求：{}", JSON.toJSONString(req));
        UserInfoQueryReq userInfoQueryReq = new UserInfoQueryReq();
        if (StringUtils.isNotBlank(req.getPhone())) {
            userInfoQueryReq.setCellularPhone(req.getPhone());
        } else if (req.getCtsIdentityType() != null && req.getCtsIdentityNum() != null) {
            userInfoQueryReq
                    .setCtsIdentityNum(req.getCtsIdentityNum())
                    .setCardType(req.getCtsIdentityType());
        } else if (StringUtils.isNotBlank(req.getCtsLogin())) {
            userInfoQueryReq
                    .setCtsLogin(req.getCtsLogin());
        } else {
            throw new BusinessException(SystemError.SYS_402);
        }
        Result<Contact> contactResult = starVipUserService.userInfoQuery(userInfoQueryReq);
        if (!contactResult.isSuccess()) throw new BusinessException(SystemError.getDefined(contactResult.getCode()));
        if (contactResult.getData() == null)
            throw new BusinessException(SystemError.STAR_VIP_20003);
        Contact contact = contactResult.getData();
        if (contact.getListOfLoyMember() == null ||
                CollectionUtils.isEmpty(contact.getListOfLoyMember().getLoyMember()))
            throw new BusinessException(SystemError.STAR_VIP_20004);
        LoyMember member = contactResult.getData().getListOfLoyMember().getLoyMember().get(0);
        UserMemberBasicInformationDTO dto = new UserMemberBasicInformationDTO();
        dto.setId(member.getId());
        dto.setMemberNumber(member.getMemberNumber());
        dto.setMemberName(contact.getCtsLastName() + contact.getCtsFstName());
        dto.setMemberPhone(contact.getCellularPhone());
        dto.setMemberEmail(contact.getEmailAddress());
        dto.setPoint1Value(member.getPoint1Value());
        dto.setCtsLogin(member.getCtsLogin());
        if (member.getListOfLOYMemberDominantTier() != null
                && CollectionUtils.isNotEmpty(member.getListOfLOYMemberDominantTier().getLoyMemberDominantTier())) {
            LoyMemberDominantTier loyMemberDominantTier = member.getListOfLOYMemberDominantTier().getLoyMemberDominantTier().get(0);
            dto.setMemberTier(loyMemberDominantTier.getTier());
            dto.setMemberTierCode(loyMemberDominantTier.getTierCode());
        }
        return Result.success(dto);
    }
    @Override
    public Result transactionIntegral(TransactionIntegralReq req) {
        //先校验会员信息 验证密码
        log.info("【星赏會VIP-交易】交易入参請求：{}", JSON.toJSONString(req));
        Result<LoyTransaction> transaction = null;
        try {
            Result<Contact> result = starVipMemberService.membershipVerification(
                    new MembershipVerificationReq()
                            .setCtsLogin(req.getCtsLogin())
                            .setCtsPassword(MD5Util.stringMd5(req.getCtsPassword()))
            );
            log.info("【星赏會VIP-交易】校验会员信息响应：{}", JSON.toJSONString(result));
            if (!result.isSuccess())
                throw new BusinessException(SystemError.getDefined(result.getCode()));
            Contact data = result.getData();
            if (Objects.isNull(data))
                throw new BusinessException(SystemError.STAR_VIP_20003);
            if (data.getListOfLoyMember() == null
                    || CollectionUtils.isEmpty(data.getListOfLoyMember().getLoyMember())) {
                throw new BusinessException(SystemError.STAR_VIP_20004);
            }
            LoyMember loyMember = data.getListOfLoyMember().getLoyMember().get(0);
            //校验可用点数
            String point1Value = loyMember.getPoint1Value();
            BigDecimal usable = BigDecimal.valueOf(
                    Optional.of(Integer.valueOf(point1Value)).orElse(0)
            );
            if (usable.compareTo(req.getPoints()) < 0) {
                throw new BusinessException(SystemError.STAR_VIP_20005);
            }
            //发起交易请求
            log.info("【星赏會VIP-交易】交易請求：{}", JSON.toJSONString(req));
            transaction = transactionService.transaction(new StarVipTransactionReq(
                    req.getPoints(), loyMember.getMemberNumber(), loyMember.getId(),
                    LocalDateTime.now(), StarVipTransactionSubType.PRODUCT, StarVipTransactionType.REDEMPTION,
                    req.getOrderNumber()
            ));
            log.info("【星赏會VIP-交易】交易响应：{}", JSON.toJSONString(req));
        } catch (BusinessException e) {
            log.error("【星赏會VIP-交易】业务异常", e);
            transaction = transaction.failed(SystemError.getDefined(e.getCode()));
        } catch (Exception e) {
            log.error("【星赏會VIP-交易】业务运行异常", e);
            transaction = transaction.failed(SystemError.SYS_500);
        }
        return transaction;
    }

    @Override
    public Result transaction(TransactionReq req) {
        log.info("【星赏會VIP-交易】交易入参請求：{}", JSON.toJSONString(req));
        Result<LoyTransaction> transaction = null;
        try {
            UserInfoQueryReq userInfoQueryReq = new UserInfoQueryReq();
            userInfoQueryReq.setCellularPhone(req.getCtsPhone());
            Result<Contact> contactResult = starVipUserService.userInfoQuery(userInfoQueryReq);
            if (!contactResult.isSuccess()) throw new BusinessException(SystemError.getDefined(contactResult.getCode()));
            if (contactResult.getData() == null)
                throw new BusinessException(SystemError.STAR_VIP_20003);
            Contact contact = contactResult.getData();
            if (contact.getListOfLoyMember() == null ||
                    CollectionUtils.isEmpty(contact.getListOfLoyMember().getLoyMember()))
                throw new BusinessException(SystemError.STAR_VIP_20004);
            LoyMember loyMember = contactResult.getData().getListOfLoyMember().getLoyMember().get(0);
            //校验可用点数
            String point1Value = loyMember.getPoint1Value();
            BigDecimal usable = BigDecimal.valueOf(
                    Optional.of(Integer.valueOf(point1Value)).orElse(0)
            );
            if (usable.compareTo(req.getPoints()) < 0) {
                throw new BusinessException(SystemError.STAR_VIP_20005);
            }
            //发起交易请求
            log.info("【星赏會VIP-交易】交易請求：{}", JSON.toJSONString(req));
            transaction = transactionService.transaction(new StarVipTransactionReq(
                    req.getPoints(), loyMember.getMemberNumber(), loyMember.getId(),
                    LocalDateTime.now(), StarVipTransactionSubType.PRODUCT, StarVipTransactionType.REDEMPTION,
                    req.getOrderNumber()
            ));
            log.info("【星赏會VIP-交易】交易响应：{}", JSON.toJSONString(req));
        } catch (BusinessException e) {
            log.error("【星赏會VIP-交易】业务异常", e);
            transaction = transaction.failed(SystemError.getDefined(e.getCode()));
        } catch (Exception e) {
            log.error("【星赏會VIP-交易】业务运行异常", e);
            transaction = transaction.failed(SystemError.SYS_500);
        }
        return transaction;
    }

    @Override
    public Result transactionIntegralTwo(TransactionIntegralReq req) {
        //先校验会员信息 验证密码
        log.info("【星赏會VIP-交易】交易入参請求：{}", JSON.toJSONString(req));
        Result<LoyTransaction> transaction = null;
        try {
            Result<Contact> result = starVipMemberService.membershipVerification(
                    new MembershipVerificationReq()
                            .setCtsLogin(req.getCtsLogin())
                            .setCtsPassword(MD5Util.stringMd5(req.getCtsPassword()))
            );
            log.info("【星赏會VIP-交易】校验会员信息响应：{}", JSON.toJSONString(result));
            if (!result.isSuccess())
                throw new BusinessException(SystemError.getDefined(result.getCode()));
            Contact data = result.getData();
            if (Objects.isNull(data))
                throw new BusinessException(SystemError.STAR_VIP_20003);
            if (data.getListOfLoyMember() == null
                    || CollectionUtils.isEmpty(data.getListOfLoyMember().getLoyMember())) {
                throw new BusinessException(SystemError.STAR_VIP_20004);
            }
            LoyMember loyMember = data.getListOfLoyMember().getLoyMember().get(0);
            //校验可用点数
            String point1Value = loyMember.getPoint1Value();
            BigDecimal usable = BigDecimal.valueOf(
                    Optional.of(Integer.valueOf(point1Value)).orElse(0)
            );
            if (usable.compareTo(req.getPoints()) < 0) {
                throw new BusinessException(SystemError.STAR_VIP_20005);
            }
            //发起交易请求
            log.info("【星赏會VIP-交易】交易請求：{}", JSON.toJSONString(req));
            transaction = transactionService.transaction(new StarVipTransactionReq(
                    req.getPoints(), loyMember.getMemberNumber(), loyMember.getId(),
                    LocalDateTime.now(), StarVipTransactionSubType.PRODUCT, StarVipTransactionType.REDEMPTION,
                    req.getOrderNumber()
            ));
            log.info("【星赏會VIP-交易】交易响应：{}", JSON.toJSONString(req));
        } catch (BusinessException e) {
            log.error("【星赏會VIP-交易】业务异常", e);
            transaction = transaction.failed(SystemError.getDefined(e.getCode()));
        } catch (Exception e) {
            log.error("【星赏會VIP-交易】业务运行异常", e);
            transaction = transaction.failed(SystemError.SYS_500);
        }
        return transaction;
    }

    @Override
    public BigDecimal getHkd(Integer point) {
        if (point == null || point == 0) {
            return new BigDecimal(0).setScale(0, BigDecimal.ROUND_UP);
        }
        BigDecimal exchangeRate = mainDataCurrencyService.getExchangeRate(String.valueOf(Currency.CNY.getCode()), CurrencyRateExchangeConstant.CRM_EXCHANGE_RATE_);
        BigDecimal hkd = new BigDecimal(point / 100).multiply(exchangeRate);
        return hkd.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    @Override
    public Result transactionIntegralThree(TransactionIntegralReq req) {
        //先校验会员信息 验证密码
        log.info("【星赏會VIP-交易】交易入参請求：{}", JSON.toJSONString(req));
        Result<LoyTransaction> transaction = null;
        try {
            Result<Contact> result = starVipMemberService.membershipVerification(
                    new MembershipVerificationReq()
                            .setCtsLogin(req.getCtsLogin())
                            .setCtsPassword(req.getCtsPassword())
            );
            log.info("【星赏會VIP-交易】校验会员信息响应：{}", JSON.toJSONString(result));
            if (!result.isSuccess())
                throw new BusinessException(SystemError.getDefined(result.getCode()));
            Contact data = result.getData();
            if (Objects.isNull(data))
                throw new BusinessException(SystemError.STAR_VIP_20003);
            if (data.getListOfLoyMember() == null
                    || CollectionUtils.isEmpty(data.getListOfLoyMember().getLoyMember())) {
                throw new BusinessException(SystemError.STAR_VIP_20004);
            }
            LoyMember loyMember = data.getListOfLoyMember().getLoyMember().get(0);
            // 扣除积分才需要校验可用点数
            if("2".equals(req.getTransactionType())) {
                //校验可用点数
                String point1Value = loyMember.getPoint1Value();
                BigDecimal usable = BigDecimal.valueOf(
                        Optional.of(Integer.valueOf(point1Value)).orElse(0)
                );
                if (usable.compareTo(req.getPoints()) < 0) {
                    throw new BusinessException(SystemError.STAR_VIP_20005);
                }
            }

            //发起交易请求
            log.info("【星赏會VIP-交易】交易請求：{}", JSON.toJSONString(req));
            transaction = transactionService.transaction(new StarVipTransactionReq(
                    req.getPoints(), loyMember.getMemberNumber(), loyMember.getId(),
                    LocalDateTime.now(), StarVipTransactionSubType.PRODUCT, "1".equals(req.getTransactionType())?StarVipTransactionType.ACCRUAL:StarVipTransactionType.REDEMPTION,
                    req.getOrderNumber()
            ));
            log.info("【星赏會VIP-交易】交易响应：{}", JSON.toJSONString(req));
        } catch (BusinessException e) {
            log.error("【星赏會VIP-交易】业务异常", e);
            transaction = transaction.failed(SystemError.getDefined(e.getCode()));
        } catch (Exception e) {
            log.error("【星赏會VIP-交易】业务运行异常", e);
            transaction = transaction.failed(SystemError.SYS_500);
        }
        return transaction;
    }

    @Override
    public Result<LoyTransaction> transactionIntegralCommon(@Valid TransactionIntegralCommonReq req) {
        log.info("【星赏會VIP-C端积分交易】交易入参請求：{}", JSON.toJSONString(req));
        Result<LoyTransaction> transaction = null;
        BigDecimal usable = BigDecimal.ZERO;
        try {
            UserInfoQueryReq userInfoQueryReq = new UserInfoQueryReq();
            userInfoQueryReq.setId(req.getMemberId());
            Result<Contact> result = starVipUserService.userInfoQuery(userInfoQueryReq);
            log.info("【星赏會VIP-交易】校验会员信息响应：{}", JSON.toJSONString(result));
            if (!result.isSuccess())
                throw new BusinessException(SystemError.getDefined(result.getCode()));
            Contact data = result.getData();
            if (Objects.isNull(data))
                throw new BusinessException(SystemError.STAR_VIP_20003);
            if (data.getListOfLoyMember() == null
                    || CollectionUtils.isEmpty(data.getListOfLoyMember().getLoyMember())) {
                throw new BusinessException(SystemError.STAR_VIP_20004);
            }
            LoyMember loyMember = null;
            List<LoyMember> loyMemberList = data.getListOfLoyMember().getLoyMember();
            for (LoyMember loyMember2 : loyMemberList) {
                if(loyMember2.getId().equals(req.getMemberId())) {
                    loyMember = loyMember2;
                }
            }

            String point1Value = loyMember.getPoint1Value();
            usable = BigDecimal.valueOf(
                    Optional.of(Integer.valueOf(point1Value)).orElse(0)
            );

            ListOfLoyMemberDominantTier listOfLOYMemberDominantTier = loyMember.getListOfLOYMemberDominantTier();
            String tierCode = listOfLOYMemberDominantTier.getLoyMemberDominantTier().get(0).getTierCode();
            SystemBusinessType systemBusinessType = SystemBusinessType.parseCode(req.getSystemBusinessType());
            StarVipTransactionProduct starVipTransactionProduct = StarVipTransactionProduct.getBySystemBusinessType(systemBusinessType);
            String ctsProdDesc = starVipTransactionProduct.getPartNumberDesc() + "-"
                    + starVipTransactionProduct.getDesc() + "("
                    + ((systemBusinessType == SystemBusinessType.OUTBOUND_TRAVEL
                    || systemBusinessType == SystemBusinessType.INBOUND_TRAVEL)?"旅行團":systemBusinessType.getValue()) +  ")";


            if(1 == req.getTransactionType()) {
                //发起交易增加请求
                log.info("【星赏會VIP-C端积分增加交易】交易請求：{}", JSON.toJSONString(req));
                transaction = transactionService.transaction(new StarVipTransactionReq(
                                CalcIntegralUtil.getBigDecimalObtainByType(systemBusinessType.getCode(),
                                        Integer.valueOf(tierCode), req.getReceivableAmount()), loyMember.getMemberNumber(),
                                req.getMemberId(),LocalDateTime.now(), StarVipTransactionSubType.PRODUCT,
                                StarVipTransactionType.ACCRUAL,starVipTransactionProduct.getPartNumber(),
                                req.getReceivableAmount(),req.getOrderNumber(),null,
                                StarVipCurrencyCode.getByCode(req.getCurrency()),starVipTransactionProduct.getCode(),
                                ctsProdDesc,"Y", req.getOrderNumber() +  "-" + req.getTransactionType(),req.getOrderSource()
                        )
                );
                log.info("【星赏會VIP-C端积分增加交易】交易响应：{}", JSON.toJSONString(req));
            } else if(2 == req.getTransactionType()) {
                // 发起交易扣除请求
                // 扣除积分才需要校验可用点数
                if("2".equals(req.getTransactionType())) {
                    //校验可用点数
                    if (usable.compareTo(req.getUsePoints()) < 0) {
                        throw new BusinessException(SystemError.STAR_VIP_20005);
                    }
                }
                log.info("【星赏會VIP-C端积分扣除交易】交易請求：{}", JSON.toJSONString(req));
                transaction = transactionService.transaction(new StarVipTransactionReq(
                        req.getUsePoints(), loyMember.getMemberNumber(), req.getMemberId(),
                        LocalDateTime.now(), StarVipTransactionSubType.PRODUCT, StarVipTransactionType.REDEMPTION,
                        starVipTransactionProduct.getPartNumber(),req.getReceivableAmount(),req.getOrderNumber(),null
                        ,null,starVipTransactionProduct.getCode(),ctsProdDesc,"N",
                        req.getOrderNumber() +  "-" + req.getTransactionType(),req.getOrderSource())
                );
                log.info("【星赏會VIP-C端积分扣除交易】交易响应：{}", JSON.toJSONString(req));
            }

        } catch (BusinessException e) {
            log.error("【星赏會VIP-C端积分交易】业务异常", e);
            transaction = transaction.failed(e);
        } catch (Exception e) {
            log.error("【星赏會VIP-C端积分交易】业务运行异常", e);
            transaction = transaction.failed(SystemError.SYS_500);
        }
        if(transaction.isSuccess()) {
            transaction.getData().setPoint1Value(usable);
        }
        return transaction;
    }

    @Override
    public Result<LoyTransaction> cancelTransactionIntegralCommon(@Valid TransactionIntegralCommonReq req) {
        log.info("【星赏會VIP-C端取消积分交易】交易入参請求：{}", JSON.toJSONString(req));
        Result<LoyTransaction> transaction = null;
        BigDecimal usable = BigDecimal.ZERO;
        try {
            UserInfoQueryReq userInfoQueryReq = new UserInfoQueryReq();
            userInfoQueryReq.setId(req.getMemberId());
            Result<Contact> result = starVipUserService.userInfoQuery(userInfoQueryReq);
            log.info("【星赏會VIP-C端取消积分交易】校验会员信息响应：{}", JSON.toJSONString(result));
            if (!result.isSuccess())
                throw new BusinessException(SystemError.getDefined(result.getCode()));
            Contact data = result.getData();
            if (Objects.isNull(data))
                throw new BusinessException(SystemError.STAR_VIP_20003);
            if (data.getListOfLoyMember() == null
                    || CollectionUtils.isEmpty(data.getListOfLoyMember().getLoyMember())) {
                throw new BusinessException(SystemError.STAR_VIP_20004);
            }
            LoyMember loyMember = null;
            List<LoyMember> loyMemberList = data.getListOfLoyMember().getLoyMember();
            for (LoyMember loyMember2 : loyMemberList) {
                if(loyMember2.getId().equals(req.getMemberId())) {
                    loyMember = loyMember2;
                }
            }

            String point1Value = loyMember.getPoint1Value();
            usable = BigDecimal.valueOf(
                    Optional.of(Integer.valueOf(point1Value)).orElse(0)
            );

            ListOfLoyMemberDominantTier listOfLOYMemberDominantTier = loyMember.getListOfLOYMemberDominantTier();
            String tierCode = listOfLOYMemberDominantTier.getLoyMemberDominantTier().get(0).getTierCode();
            SystemBusinessType systemBusinessType = SystemBusinessType.parseCode(req.getSystemBusinessType());
            StarVipTransactionProduct starVipTransactionProduct = StarVipTransactionProduct.getBySystemBusinessType(systemBusinessType);
            String ctsProdDesc = starVipTransactionProduct.getPartNumberDesc() + "-"
                    + starVipTransactionProduct.getDesc() + "("
                    + ((systemBusinessType == SystemBusinessType.OUTBOUND_TRAVEL
                    || systemBusinessType == SystemBusinessType.INBOUND_TRAVEL)?"旅行團":systemBusinessType.getValue()) +  ")";


            if(1 == req.getTransactionType()) {
                //发起取消交易增加请求
                log.info("【星赏會VIP-C端取消增加积分交易】交易請求：{}", JSON.toJSONString(req));
                transaction = transactionService.cancelTransaction(new StarVipTransactionReq(
                                CalcIntegralUtil.getBigDecimalObtainByType(systemBusinessType.getCode(),
                                        Integer.valueOf(tierCode), req.getReceivableAmount()),
                        loyMember.getMemberNumber(), req.getMemberId(),
                                LocalDateTime.now(), StarVipTransactionSubType.PRODUCT, StarVipTransactionType.ACCRUAL,
                                starVipTransactionProduct.getPartNumber(),req.getReceivableAmount(),req.getOrderNumber(),
                        null, StarVipCurrencyCode.getByCode(req.getCurrency()),
                                starVipTransactionProduct.getCode(),ctsProdDesc,req.getCtsQualifyTxnFlag(),
                        req.getOrderNumber() +  "-" + (req.getTransactionType() + 2),req.getOrderSource())
                        );
                log.info("【星赏會VIP-C端取消增加积分交易】交易响应：{}", JSON.toJSONString(req));
            } else if(2 == req.getTransactionType()) {
                // 发起交易扣除请求
                log.info("【星赏會VIP-C端取消扣除积分交易】交易請求：{}", JSON.toJSONString(req));
                transaction = transactionService.cancelTransaction(new StarVipTransactionReq(
                        req.getUsePoints(), loyMember.getMemberNumber(), req.getMemberId(),
                        LocalDateTime.now(), StarVipTransactionSubType.PRODUCT, StarVipTransactionType.REDEMPTION,
                        starVipTransactionProduct.getPartNumber(),req.getReceivableAmount(),req.getOrderNumber(),null
                        ,null,starVipTransactionProduct.getCode(),ctsProdDesc,"N",
                        req.getOrderNumber() +  "-" + (req.getTransactionType() + 2),req.getOrderSource())
                );
                log.info("【星赏會VIP-C端取消扣除积分交易】交易响应：{}", JSON.toJSONString(req));
            }

        } catch (BusinessException e) {
            log.error("【星赏會VIP-C端取消积分交易】业务异常", e);
            transaction = transaction.failed(e);
        } catch (Exception e) {
            log.error("【星赏會VIP-C端取消积分交易】业务运行异常", e);
            transaction = transaction.failed(SystemError.SYS_500);
        }
        if(transaction.isSuccess()) {
            transaction.getData().setPoint1Value(usable);
        }
        return transaction;
    }

    @Override
    public BigDecimal getHkd(String memberId,BigDecimal receivableAmount) {
        log.info("【星赏會VIP-查询积分兑换港币】交易入参請求：memberId={},receivableAmount={}", memberId,receivableAmount);
        BigDecimal hkd = BigDecimal.ZERO;
        try {
            if(StringUtils.isBlank(memberId) || receivableAmount == null || BigDecimal.ZERO.compareTo(receivableAmount) == 0) {
                return hkd;
            }
            UserInfoQueryReq userInfoQueryReq = new UserInfoQueryReq();
            userInfoQueryReq.setId(memberId);
            Result<Contact> contactResult = starVipUserService.userInfoQuery(userInfoQueryReq);
            if (!contactResult.isSuccess()) throw new BusinessException(SystemError.getDefined(contactResult.getCode()));
            if (contactResult.getData() == null)
                throw new BusinessException(SystemError.STAR_VIP_20003);
            Contact contact = contactResult.getData();
            if (contact.getListOfLoyMember() == null ||
                    CollectionUtils.isEmpty(contact.getListOfLoyMember().getLoyMember()))
                throw new BusinessException(SystemError.STAR_VIP_20004);
            LoyMember loyMember = contactResult.getData().getListOfLoyMember().getLoyMember().get(0);
            //校验可用点数
            String point1Value = loyMember.getPoint1Value();
            BigDecimal usable = BigDecimal.valueOf(
                    Optional.of(Integer.valueOf(point1Value)).orElse(0)
            );
            if ( BigDecimal.ZERO.compareTo(usable) == 0) {
                return BigDecimal.ZERO;
            }
            BigDecimal exchangeRate = mainDataCurrencyService.getExchangeRate(String.valueOf(Currency.CNY.getCurrency()), CurrencyRateExchangeConstant.CRM_EXCHANGE_RATE_);
            hkd = usable.divide(new BigDecimal(100)).multiply(exchangeRate);
            if(hkd.compareTo(receivableAmount) >= 0) {
                hkd = receivableAmount;
            } else {
                hkd = hkd.setScale(2, BigDecimal.ROUND_HALF_UP);
            }
        } catch (BusinessException e) {
            log.error("【星赏會VIP-查询积分兑换港币】业务异常", e);
        } catch (Exception e) {
            log.error("【星赏會VIP-查询积分兑换港币】业务运行异常", e);
        }
        log.info("【星赏會VIP-查询积分兑换港币结果：{}", hkd);
        return hkd;
    }

    @Override
    public TrainIntegralDTO queryIntegralAndHkd(StarVipTransactionIntegralReq req) {
        log.info("【星赏會VIP-查询會員积分,当前可用积分,积分抵扣金额,金额可获得积分】交易入参請求：{}", JSON.toJSONString(req));
        TrainIntegralDTO trainIntegralDTO = new TrainIntegralDTO();
        try {
            if(StringUtils.isBlank(req.getMemberId())) {
                trainIntegralDTO.setExpectedObtain(CalcIntegralUtil.getLongObtainByType(req.getBusinessType(),1,req.getReceivableAmount()));
                return trainIntegralDTO;
            }
            UserInfoQueryReq userInfoQueryReq = new UserInfoQueryReq();
            userInfoQueryReq.setId(req.getMemberId());
            Result<Contact> contactResult = starVipUserService.userInfoQuery(userInfoQueryReq);
            if (!contactResult.isSuccess()) throw new BusinessException(SystemError.getDefined(contactResult.getCode()));
            if (contactResult.getData() == null)
                throw new BusinessException(SystemError.STAR_VIP_20003);
            Contact contact = contactResult.getData();
            if (contact.getListOfLoyMember() == null ||
                    CollectionUtils.isEmpty(contact.getListOfLoyMember().getLoyMember()))
                throw new BusinessException(SystemError.STAR_VIP_20004);
            LoyMember loyMember = contactResult.getData().getListOfLoyMember().getLoyMember().get(0);
            //校验可用点数
            String point1Value = loyMember.getPoint1Value();
            BigDecimal usable = BigDecimal.valueOf(
                    Optional.of(Integer.valueOf(point1Value)).orElse(0)
            );

            //BigDecimal exchangeRate = mainDataCurrencyService.getExchangeRate(String.valueOf(Currency.CNY.getCurrency()), CurrencyRateExchangeConstant.CRM_EXCHANGE_RATE_);
            BigDecimal exchangeRate = req.getExchangeRate();
            BigDecimal hkd = usable.divide(new BigDecimal(100)).multiply(exchangeRate);
            if(hkd.compareTo(req.getReceivableAmount()) >= 0) {
                hkd = req.getReceivableAmount();
            } else {
                hkd = hkd.setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            trainIntegralDTO.setDeduction(hkd);
            trainIntegralDTO.setAvailable(usable.longValue());
            trainIntegralDTO.setSurplus(usable.longValue());
            if(req.getBusinessType() != null) {
                ListOfLoyMemberDominantTier listOfLOYMemberDominantTier = loyMember.getListOfLOYMemberDominantTier();
                String tierCode = listOfLOYMemberDominantTier.getLoyMemberDominantTier().get(0).getTierCode();
                trainIntegralDTO.setExpectedObtain(CalcIntegralUtil.getLongObtainByType(req.getBusinessType(),Integer.valueOf(tierCode),req.getReceivableAmount()));
            }
        } catch (BusinessException e) {
            log.error("【星赏會VIP-查询會員积分,当前可用积分,积分抵扣金额,金额可获得积分】业务异常", e);
        } catch (Exception e) {
            log.error("【星赏會VIP-查询會員积分,当前可用积分,积分抵扣金额,金额可获得积分】业务运行异常", e);
        }
        log.info("【星赏會VIP-查询會員积分,当前可用积分,积分抵扣金额,金额可获得积分结果：{}", JSON.toJSONString(trainIntegralDTO));
        return trainIntegralDTO;
    }

}
